﻿using Devonline.Core;
using Microsoft.Extensions.DependencyInjection;

namespace Devonline.Caching;

/// <summary>
/// IMemoryCache: 内存中缓存
/// IDistributedCache: 分布式缓存
/// HybridCache: 混合缓存, 提供了 GetOrCreateAsync 直接访问或写入能力, 但在 .net9 才可以使用
/// https://learn.microsoft.com/zh-cn/aspnet/core/performance/caching/hybrid?view=aspnetcore-9.0
/// </summary>
public static class ServiceExtensions
{
    /// <summary>
    /// 注入 缓存
    /// </summary>
    /// <param name="services">依赖注入服务</param>
    /// <param name="cacheSetting">缓存配置</param>
    public static IServiceCollection AddDistributedCache(this IServiceCollection services, CacheSetting? cacheSetting = default)
    {
        if (cacheSetting is null || string.IsNullOrWhiteSpace(cacheSetting.Configuration))
        {
            services.AddDistributedMemoryCache();
        }
        else
        {
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = cacheSetting.Configuration;
                options.InstanceName = cacheSetting.Prefix;
            });
        }

        return services;
    }

    /// <summary>
    /// 注入 缓存
    /// </summary>
    /// <param name="services">依赖注入服务</param>
    /// <param name="cacheSetting">缓存配置</param>
    public static IServiceCollection AddHybridCache(this IServiceCollection services, CacheSetting cacheSetting)
    {
        services.AddDistributedCache(cacheSetting);
        services.AddHybridCache(options =>
        {
            options.DefaultEntryOptions = new Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions
            {
                Expiration = TimeSpan.FromSeconds(cacheSetting.ExpireTime),
                LocalCacheExpiration = TimeSpan.FromSeconds(cacheSetting.ReserveTime)
            };
        });
        return services;
    }
}